package com.dc.web.controller;


import com.dc.constant.MessageConstant;
import com.dc.dao.ShipDao;
import com.dc.dao.ShipRepairDao;
import com.dc.dao.WorkflowElectricBoxDao;
import com.dc.entity.ShipEntity;
import com.dc.entity.ShipRepairEntity;
import com.dc.entity.WorkflowElectricBoxEntity;
import com.dc.entity.WorkflowWaterCleanChildEntity;
import com.dc.exception.ServiceException;
import com.dc.model.AjaxResult;
import com.dc.model.WorkflowElectricBoxPowerBody;
import com.dc.model.WorkflowListBody;
import com.dc.service.CalibrationService;
import com.dc.service.HttpService2;
import com.dc.service.dto.electronic.HttpGetPowerReturnNewBody;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@Api(tags = "移动电箱")
@RequestMapping("/api/workflow_electric_box")
@RestController
public class WorkflowElectricBoxController {

    @Resource
    WorkflowElectricBoxDao workflowElectricBoxDao;

    @Resource
    ShipRepairDao shipRepairDao;

    @Resource
    ShipDao shipDao;

    @Resource
    CalibrationService calibrationService;

    @Resource
    HttpService2 httpService2;

    @GetMapping("/list")
    public AjaxResult list(WorkflowListBody body) {

        Integer pageNumber = body.getPageNumber();
        pageNumber = ObjectUtils.defaultIfNull(pageNumber, 1);
        Integer pageSize = body.getPageSize();
        pageSize = ObjectUtils.defaultIfNull(pageSize, 20);

        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);

        Long repairId = body.getRepairId();     // 维修工单id

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(repairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        Page<WorkflowElectricBoxEntity> resultList = workflowElectricBoxDao.findByShipRepairEntity(shipRepairEntity, pageRequest);

        resultList.getContent().forEach(t -> {
            dynamicCalc(t, shipEntity, shipRepairEntity);
        });

        return AjaxResult.success(resultList);
    }

    @GetMapping("/{id}")
    public AjaxResult show(@PathVariable("id") Long id) {

        Optional<WorkflowElectricBoxEntity> optional = workflowElectricBoxDao.findById(id);
        if(!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowElectricBoxEntity machinePipeEntity = optional.get();

        ShipRepairEntity shipRepairEntity = machinePipeEntity.getShipRepairEntity();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);

        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        dynamicCalc(machinePipeEntity, shipEntity, shipRepairEntity);

        return AjaxResult.success(machinePipeEntity);
    }

    @PostMapping()
    public AjaxResult add(@RequestHeader HttpHeaders httpHeaders, @RequestBody WorkflowElectricBoxEntity entity) {

        entity.setId(null);

        Long shipRepairId = entity.getShipRepairId();
        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        entity.setShipRepairEntity(shipRepairEntity);

        WorkflowElectricBoxEntity save = workflowElectricBoxDao.save(entity);

        dynamicCalc(save, shipEntity, shipRepairEntity);

        return AjaxResult.success(save);
    }

    /**
     * 只更新编号
     * @param id
     * @param entity
     * @return
     */
    @PutMapping("/{id}")
    public AjaxResult update(@PathVariable("id") Long id, @RequestBody WorkflowElectricBoxEntity entity) {

        Optional<WorkflowElectricBoxEntity> optionalElectricBox = workflowElectricBoxDao.findById(id);
        if(!optionalElectricBox.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }
        WorkflowElectricBoxEntity electricBoxEntity = optionalElectricBox.get();

//        Long shipRepairId = entity.getShipRepairId();
//        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
//        if(!optionalShipRepair.isPresent()) {
//            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
//        }
//
//        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();
//
//        Long shipId = shipRepairEntity.getShipId();
//        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
//        if(!optionalShip.isPresent()) {
//            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
//        }
//
//        ShipEntity shipEntity = optionalShip.get();
//
//        entity.setShipRepairEntity(shipRepairEntity);

        electricBoxEntity.setElectricBoxNo(entity.getElectricBoxNo());
        electricBoxEntity.setRoom(entity.getRoom());
        electricBoxEntity.setMfid(entity.getMfid());
        electricBoxEntity.setPower(entity.getPower());

        WorkflowElectricBoxEntity save = workflowElectricBoxDao.save(electricBoxEntity);

//        dynamicCalc(save, shipEntity, shipRepairEntity);

        return AjaxResult.success(save);
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {

        workflowElectricBoxDao.deleteById(id);

        return AjaxResult.success();
    }


    @Deprecated
//    @PostMapping("/child/sync")
    public AjaxResult syncChildPower(@RequestBody WorkflowElectricBoxPowerBody entity) {

        Long shipRepairId = entity.getShipRepairId();
        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Date startTime = shipRepairEntity.getEnterTime();
        Date endTime = shipRepairEntity.getOutTime();
        String mfid = entity.getMfid();
        Set<String> mfids = new HashSet<>();
        mfids.add(mfid);
        Map<String, HttpGetPowerReturnNewBody> powerMapByHourType = httpService2.getPowerListByHourType(mfids, startTime, endTime);

        HttpGetPowerReturnNewBody body = powerMapByHourType.get(mfid);
        Double power = 0.;
        if(ObjectUtils.isNotEmpty(body)) {
            power = body.getSum();
        }

        return AjaxResult.success(power);

    }


    @GetMapping("/child/sync/{id}")
    public AjaxResult syncChildPower(@PathVariable("id") Long id) {
        Optional<WorkflowElectricBoxEntity> optional = workflowElectricBoxDao.findById(id);
        if(!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SYNC_WORKFLOW_MISSION);
        }
        WorkflowElectricBoxEntity entity = optional.get();

        ShipRepairEntity shipRepairEntity = entity.getShipRepairEntity();

        entity.setShipRepairId(shipRepairEntity.getId());

        Date startTime = shipRepairEntity.getEnterTime();
        Date endTime = shipRepairEntity.getOutTime();
        String deviceNo = entity.getElectricBoxNo();
        String mfid = entity.getMfid();
        Set<String> mfids = new HashSet<>();
        mfids.add(mfid);
        Map<String, HttpGetPowerReturnNewBody> powerMapByHourType = httpService2.getPowerListByHourType(mfids, startTime, endTime);

        HttpGetPowerReturnNewBody body = powerMapByHourType.get(mfid);
        double power = 0.;
        if(ObjectUtils.isNotEmpty(body)) {
            power = body.getSum();
        }

        entity.setPower(power);

        WorkflowElectricBoxEntity save = workflowElectricBoxDao.save(entity);

        return AjaxResult.success(save);

    }



    /////////////////////////////////////////////////////

    private WorkflowElectricBoxEntity dynamicCalc(
            WorkflowElectricBoxEntity entity,
            ShipEntity shipEntity,
            ShipRepairEntity shipRepairEntity) {

//        entity.setShipName(shipEntity.getName());
//        entity.setReporter(shipRepairEntity.getUpdater());
        entity.setShipRepairId(shipRepairEntity.getId());



        return entity;
    }
}
